<?php
/**
 *@file comment.php
 *@author Zhe.Zhou(zhouzhe@haibao.com)
 *@date 2015-7-29 下午4:19:39
 *@brief  
 */
namespace haibao\app\business;

class Comment extends Base{
    
    /**
     * @var $_instance
     */
    private static $_instance;
    
    /**
     * instance()
     */
    private static function instance(){
        if(!self::$_instance){
            self::$_instance = new \haibao\app\data\Comment();
        }
        return self::$_instance;
    }
    
    public static function getCommentById($commentId){
        return self::instance()->getCommentById($commentId);
    }
    
	public static function getCommentList($commentFilter){
		return self::instance()->getAll($commentFilter);
	}
	
	public static function getNewCommentList($articleId, $commentId = null){
	    if(!$articleId){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    $commentList = self::instance()->getNewCommentList($articleId, $commentId);
	    if($commentList){
	        $userIdArr = array();
	        foreach($commentList as $mainComment){
	            array_push($userIdArr, $mainComment['fromUserId']);
	            if(array_key_exists('children', $mainComment)){
	                foreach($mainComment['children'] as $comment){
	                    array_push($userIdArr, $comment['fromUserId']);
	                    array_push($userIdArr, $comment['toUserId']);
	                }
	            }
	        }
	        $userIdArr = array_unique($userIdArr);
	        $nickNameArr = array();
	        if($userIdArr){
	            $nickNameArr = \haibao\app\business\Authuser::getNicknameByUserIdArr($userIdArr);
	        }
    	    foreach($commentList as &$mainComment){
    	        if(!isset($nickNameArr[$mainComment['fromUserId']])){
    	            continue;
    	        }
	            $mainComment['fromUsername'] = $nickNameArr[$mainComment['fromUserId']];
	            if(array_key_exists('children', $mainComment)){
	                foreach($mainComment['children'] as &$comment){
	                    $comment['fromUsername'] = $nickNameArr[$comment['fromUserId']];
	                    $comment['toUsername'] = $nickNameArr[$comment['toUserId']];
	                }
	            }
	        }
	    }
	    return $commentList;
	}
	
	public static function getCommentByMainCommentId($articleId, $mainCommentId){
	    if(!$articleId || !$mainCommentId){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    $commentList = self::instance()->getCommentData($articleId, array($mainCommentId));
	    return array_key_exists($mainCommentId, $commentList) ? $commentList[$mainCommentId] : array();
	}
	
	public static function updateComment($id,$arrSet){
		\haibao\cms\business\Base::checkOperation(\haibao\cms\business\Base::FUNC_CODE_APP_COMMENT);
		$arrSet['CreateTime'] = date('Y-m-d H:i:s');
		$arrSet['CreateBy'] = self::getCurrentUser()->Id;
		self::instance()->updateByCommentId($id, $arrSet);
		self::instance()->updateCommentCount($id);
		if(is_array($id)){
		    foreach($id as $key=>$val){
		        $comment = self::instance()->getCommentById($val);
		        if($comment){
		            self::instance()->deleteCommentCache($comment->ObjectId);
		        }
		    }
		}else{
		    $comment = self::instance()->getCommentById($id);
		    if($comment){
		        self::instance()->deleteCommentCache($comment->ObjectId);
		    }
		}
		\haibao\cms\business\Base::saveOperateHistory(\haibao\cms\business\Base::FUNC_CODE_APP_COMMENT, $arrSet);
	}
	
	public static function updateArticleCommentNum($commentId,$type){
		self::instance()->updateArticleCommentNum($commentId,$type);
	}
	
	public static function updateCommentCount($commentId){
	    self::instance()->updateCommentCount($commentId);
	}
	
	public static function getCommentCountByArticleId($articleId){
		if(!$articleId){
			throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
		}
	    return self::instance()->getCommentCountByArticleId($articleId);
	}
	
	/**
	 * 发表评论
	 * @param \haibao\app\model\data\Comments $model
	 */
	public static function saveComment($model){
	    if(!$model->UserId || !$model->ObjectId || !trim($model->Content)){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    
	    if(self::isBan($model->UserId)){
	        throw new BusinessException('你已经被系统禁言，暂时不能评论', self::DATA_ERROR_CODE_CONTENT_USER_CLOSE);
	    }
	    
	    if(!\haibao\app\business\Article::getOneById($model->ObjectId)){
	        throw new BusinessException('文章不存在', self::DATA_ERROR_CODE_ARTICLE_ERROR);
	    }
	    
	    self::packModel($model);
	    self::instance()->saveComment($model);
	}
	
	/**
	 * 3.1.0 发表评论
	 */
	public static function saveNewComment($userId, $articleId, $content, $replyCommentId = null){
	    if(!$userId || !$articleId || !trim($content)){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    if(self::isBan($userId)){
	        throw new BusinessException('你已经被系统禁言，暂时不能评论', self::DATA_ERROR_CODE_CONTENT_USER_CLOSE);
	    }
	    $article = \haibao\app\business\Article::getOneById($articleId);
	    if(!$article){
	        throw new BusinessException('文章不存在', self::DATA_ERROR_CODE_ARTICLE_ERROR);
	    }
	    $model = new \haibao\app\model\data\Comments();
	    $model->ObjectId = $articleId;
	    $model->ObjectType = $article->Type;
	    $model->Content = json_encode($content);
	    $model->UserId = $userId;
	    
	    $user = \haibao\app\business\Authuser::getUserByUserId($userId);
	    if(!$user){
	        throw new BusinessException('用户不存在', self::DATA_ERROR_CODE_USER_NOTHAS);
	    }
	    $model->Nickname = isset($user->NickName) ? $user->NickName : $user->UserName;
	    $model->AddTime = new \DateTime();
	    $model->Status = \haibao\app\model\data\Comments::STATUS_OK;
	    
	    $parentComment = null;
	    if($replyCommentId){
	        $parentComment = self::getCommentById($replyCommentId);
	        if(!$parentComment || $parentComment->Status == \haibao\app\model\data\Comments::STATUS_DEL){
	            throw new BusinessException('回复的评论已被删除', self::DATA_ERROR_CODE_ARTICLE_ERROR);
	        }
	        $model->MainCommentId = !empty($parentComment->MainCommentId) ? $parentComment->MainCommentId : $parentComment->Id;
	        $model->ReplyCommentId = $replyCommentId;
	        $model->ReplyUserId = $parentComment->UserId;
	    }
	    self::instance()->saveComment($model);
	    return $model->Id;
	}
	
	/**
	 * 删除回复评论
	 */
	public static function deleteReplyComment($commentIdArr){
	    if(!$commentIdArr){
	        return false;
	    }
	    $commentIdArr = array_filter(array_unique($commentIdArr));
	    self::instance()->setCommentRead($commentIdArr, \haibao\app\model\data\Comments::IS_READ_DELETE);
	}
	
	/**
	 * 删除自己的评论
	 */
	public static function deleteComment($userId, $commentId){
	    if(!$userId || !$commentId){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    self::instance()->deleteComment($userId, $commentId);
	}
	
	/**
	 * 用户是否被禁止评论
	 * @param int $userId
	 */
	public static function isBan($userId){
	    $banUser = \haibao\app\business\CommentBan::getBanById($userId);
	    return !empty($banUser) ? true : false;
	}
	
	/**
	 * @param \haibao\app\model\data\Comments $model
	 */
	private static function packModel($model){
	    $model->ObjectType = \haibao\app\model\data\Comments::OBJ_TYPE_ARTICLE;
	    
	    $user = \haibao\app\business\Authuser::getUserByUserId($model->UserId);
	    if(!$user){
	        throw new BusinessException('用户不存在', self::DATA_ERROR_CODE_USER_NOTHAS);
	    }
	    $model->Nickname = $user->NickName ? $user->NickName : $user->UserName;
	    
	    $model->AddTime = new \DateTime();
	    $model->Status = \haibao\app\model\data\Comments::STATUS_OK;
	}
}